{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "## 4.4 用于数组的文件输入输出 File Input and Output with Arrays"
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "source": [
    "# 模块导入\r\n",
    "import os\r\n",
    "import sys\r\n",
    "sys.path.append(os.path.dirname(os.getcwd()))\r\n",
    "import numpy\r\n",
    "from dependency import arr_info"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 4.4.1 Storing Arrays on Disk in Binary Format 将数组以二进制格式保存到硬盘\r\n",
    "\r\n",
    "+ `numpy.save()`：保存原始数据（未压缩），默认以非压缩的原始二进制数据保存，扩展名为 .npy；\r\n",
    "+ `numpy.savez()`：保存压缩数据，扩展名为 .npz；\r\n",
    "+ `numpy.load()`：加载数据"
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "source": [
    "# 保存与读取原始数据\r\n",
    "\r\n",
    "ary1_1 = numpy.arange(1, 13).reshape(3, 4)      # 二维数组\r\n",
    "ary1_2 = numpy.arange(1, 61).reshape(3, 4, 5)   # 三维数组\r\n",
    "arr_info([ary1_1, ary1_2])\r\n",
    "file_path_1 = os.getcwd() + \"\\\\data\\\\data1_1.npy\"  # 即使不写扩展名，Numpy 也会自动加上：.npy\r\n",
    "file_path_2 = os.getcwd() + \"\\\\data\\\\data1_2.npz\"  # 即使不写扩展名，Numpy 也会自动加上：.npz\r\n",
    "\r\n",
    "# 保存原始文件\r\n",
    "numpy.save(file_path_1, ary1_1)\r\n",
    "print(\"已保存:\", file_path_1)\r\n",
    "\r\n",
    "# 读取原始文件\r\n",
    "ary1_3 = numpy.load(file_path_1)      # 读取的时候路径中文件名必须包含文件扩展名\r\n",
    "arr_info([ary1_3])\r\n",
    "\r\n",
    "# 保存压缩文件\r\n",
    "numpy.savez(file_path_2, array_A=ary1_1, array_B=ary1_2)    # 可以保存多个数组\r\n",
    "\r\n",
    "# 读取压缩文件\r\n",
    "ary1_4 = numpy.load(file_path_2)      # 读取的时候路径中文件名必须包含文件扩展名\r\n",
    "arr_info([ ary1_4[\"array_A\"], ary1_4[\"array_B\"] ])  # 以字典的形式分别调用"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "【1】\n",
      " 多维数组（ndarray）:\n",
      " [[ 1  2  3  4]\n",
      " [ 5  6  7  8]\n",
      " [ 9 10 11 12]]\n",
      " 数组维数（ndim）: 2\n",
      " 维度元组（shape）: (3, 4)\n",
      " 数据类型（dtype）: int32\n",
      "【2】\n",
      " 多维数组（ndarray）:\n",
      " [[[ 1  2  3  4  5]\n",
      "  [ 6  7  8  9 10]\n",
      "  [11 12 13 14 15]\n",
      "  [16 17 18 19 20]]\n",
      "\n",
      " [[21 22 23 24 25]\n",
      "  [26 27 28 29 30]\n",
      "  [31 32 33 34 35]\n",
      "  [36 37 38 39 40]]\n",
      "\n",
      " [[41 42 43 44 45]\n",
      "  [46 47 48 49 50]\n",
      "  [51 52 53 54 55]\n",
      "  [56 57 58 59 60]]]\n",
      " 数组维数（ndim）: 3\n",
      " 维度元组（shape）: (3, 4, 5)\n",
      " 数据类型（dtype）: int32\n",
      "已保存: c:\\Git-Station\\PyDAV\\Python for Data Analysis\\4. NumPy Basics - Arrays and Vectorized Computation\\data\\data1_1.npy\n",
      "【1】\n",
      " 多维数组（ndarray）:\n",
      " [[ 1  2  3  4]\n",
      " [ 5  6  7  8]\n",
      " [ 9 10 11 12]]\n",
      " 数组维数（ndim）: 2\n",
      " 维度元组（shape）: (3, 4)\n",
      " 数据类型（dtype）: int32\n",
      "【1】\n",
      " 多维数组（ndarray）:\n",
      " [[ 1  2  3  4]\n",
      " [ 5  6  7  8]\n",
      " [ 9 10 11 12]]\n",
      " 数组维数（ndim）: 2\n",
      " 维度元组（shape）: (3, 4)\n",
      " 数据类型（dtype）: int32\n",
      "【2】\n",
      " 多维数组（ndarray）:\n",
      " [[[ 1  2  3  4  5]\n",
      "  [ 6  7  8  9 10]\n",
      "  [11 12 13 14 15]\n",
      "  [16 17 18 19 20]]\n",
      "\n",
      " [[21 22 23 24 25]\n",
      "  [26 27 28 29 30]\n",
      "  [31 32 33 34 35]\n",
      "  [36 37 38 39 40]]\n",
      "\n",
      " [[41 42 43 44 45]\n",
      "  [46 47 48 49 50]\n",
      "  [51 52 53 54 55]\n",
      "  [56 57 58 59 60]]]\n",
      " 数组维数（ndim）: 3\n",
      " 维度元组（shape）: (3, 4, 5)\n",
      " 数据类型（dtype）: int32\n"
     ]
    }
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 4.4.2 保存与读取文本文件 Saving and Loading Text Files\r\n",
    "\r\n",
    "+ `numpy.loadtxt()`：读取文本文件\r\n",
    "+ `numpy.savetxt()`：保存文本文件"
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "source": [
    "# 保存和读取文本文件\r\n",
    "\r\n",
    "# 读取文本文件\r\n",
    "file_path_3 = os.getcwd() + \"\\\\data\\\\data2_1.txt\"\r\n",
    "ary2_1 = numpy.loadtxt(file_path_3, delimiter=\",\")\r\n",
    "ary2_2 = numpy.loadtxt(file_path_3, delimiter=\",\", unpack=True)\r\n",
    "arr_info([ary2_1, ary2_2])\r\n",
    "\r\n",
    "# 保存文本文件\r\n",
    "numpy.savetxt(os.getcwd() + \"\\\\data\\\\data1_1.txt\", ary1_1, delimiter=\"\\t\")      # 必须手动指定后缀名\r\n",
    "numpy.savetxt(os.getcwd() + \"\\\\data\\\\data1_2.txt\", ary1_2[0], delimiter=\"\\t\")  # 三维数组不能直接保存，必须降维至二维、一维\r\n",
    "numpy.savetxt(os.getcwd() + \"\\\\data\\\\data2_3.csv\", ary2_1, delimiter=\"\\t\")      # 保存的文件格式也可以是 .csv 等其他文本格式"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "【1】\n",
      " 多维数组（ndarray）:\n",
      " [[300. 320. 330. 340. 350. 360. 370. 380. 390. 400.]\n",
      " [  1.   2.   0.   3.  10.   2.   3.   2.   1.   4.]]\n",
      " 数组维数（ndim）: 2\n",
      " 维度元组（shape）: (2, 10)\n",
      " 数据类型（dtype）: float64\n"
     ]
    }
   ],
   "metadata": {}
  }
 ],
 "metadata": {
  "orig_nbformat": 4,
  "language_info": {
   "name": "python",
   "version": "3.9.6",
   "mimetype": "text/x-python",
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "pygments_lexer": "ipython3",
   "nbconvert_exporter": "python",
   "file_extension": ".py"
  },
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3.9.6 64-bit ('venv': venv)"
  },
  "interpreter": {
   "hash": "2df30c634058628fc5df5036be3dee25b811a252316c0aa1ff7f50eb8aecb5be"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}